//
//  SJEmoticonViewController.swift
//  表情处理
//
//  Created by app;e on 15/10/16.
//  Copyright © 2015年 world. All rights reserved.
//

import UIKit

private let SJEmoticonReusableCellIdentifier = "SJEmoticonReusableCellIdentifier"

class SJEmoticonViewController: UIViewController {

    ///选中表情的 回调
    var didSelectedEmotionCallBack:(emoticon:SJEmoticon)->()
    
    ///选中表情的闭包 初始化 一个 表情控制器
    init(didSelectedEmoticon:(emotion:SJEmoticon)->()){
        //记录闭包
        didSelectedEmotionCallBack = didSelectedEmoticon
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

    /// 表情数组 数据 (三组 + 最近)
    private lazy var packages = SJEmoticonPackage.packageList
    
    override func viewDidLoad() {
        super.viewDidLoad()
       view.backgroundColor = UIColor.redColor()
        prepareForUI()
        //加载表情包
       let pages = SJEmoticonPackage.packageList
//        for p in pages {
//            print("\(p.emoticons?.count) + \(p.groupName)")
//        }
        
    }
    //选中表情分组 的回调方法
    func selectedItem(item:UIBarButtonItem){
        let indexPath = NSIndexPath(forItem:0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    //准备UI(做第三方框架,最好不要使用第三方框架)
    private func prepareForUI(){
        view.addSubview(collectionView)
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.pagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
        
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor.orangeColor()
        //布局
        //取消autosizing
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        //约束数组
        var cons = [NSLayoutConstraint]()
        let viewsDict = ["toolBar":toolBar,"collectionView":collectionView]
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: viewsDict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: viewsDict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict)
        
        view.addConstraints(cons)
        
        prepareForToolBar()
        prepareForCollectionView()
    }
    
    //准备工具条
    private func prepareForToolBar(){
        //创建数组
        var items = [UIBarButtonItem]()
//        let titles = ["最近","默认","emoji","浪小花"]
        var index = 0
        for pack in packages {
            let item = UIBarButtonItem(title: pack.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "selectedItem:")
            item.tag = index++
            items.append(item)
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    //准备collectionView
    private func prepareForCollectionView(){
        collectionView.userInteractionEnabled = true
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(SJEmoticonCell.self, forCellWithReuseIdentifier: SJEmoticonReusableCellIdentifier)
    }
    
    //工具条
    lazy var toolBar = UIToolbar()
    //collectionView
   
    lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: SJEmoticonLayout())
    
    //MARK : - 私有的layout布局类
    private class SJEmoticonLayout:UICollectionViewFlowLayout {
        //在collectionView的大小确定之后,  item布局之前会调用一次
        private override func prepareLayout() {
            //记得调用父类的方法
            super.prepareLayout()
            let wh = collectionView!.bounds.width / 7
            itemSize = CGSizeMake(wh, wh)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            
            //计算上下的inset
            let inset = (collectionView!.bounds.height - 3 * wh ) * 0.5
            sectionInset = UIEdgeInsets(top: inset, left: 0, bottom: inset, right: 0)
        }
    }

}

// MARK: - collectionView的数据源方法
extension SJEmoticonViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    //返回 组 的数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    //返回 每组  多少表情
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SJEmoticonReusableCellIdentifier, forIndexPath: indexPath) as! SJEmoticonCell
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //获取用户选中的 表情
        let emotion = packages[indexPath.section].emoticons![indexPath.item]
        
        // 如果表情不为空,则添加到最近表情包中
        if emotion.chs != nil || emotion.emoji != nil{
            emotion.times += 1
            //从表情数组中取出最近表情
            packages[0].addFavouriteEmoticon(emotion)
        }
        
        //执行 block 回调方法
        didSelectedEmotionCallBack(emoticon: emotion)
    }
    
}

// MARK: - 自定义collectionView的cell
private class SJEmoticonCell:UICollectionViewCell{

    ///表情模型   一个 cell对应一个表情模型
    var emoticon:SJEmoticon?{
        didSet{
            //设置图片 (根据表情模型  给 cell 中的emotionButton 设置 表情 图片)
//            print(emoticon?.imagePath)
            if let path = emoticon?.imagePath {
                emotionButton.setImage(UIImage(contentsOfFile: path), forState: UIControlState.Normal)
            }else{
                //防止cell 重用
                emotionButton.setImage(nil, forState: UIControlState.Normal)
            }
            //使用这种方法,当来回滚动的时候 cell重用 emoji表情与其他表情会发混乱.因为emoji表情是设置button的title,其他表情是设置button的image.解决办法如下:当emoji没有值的时候把title置空
            emotionButton.setTitle(emoticon!.emoji ?? "", forState: UIControlState.Normal)
//            if emoticon?.code != nil {
//                emotionButton.setTitle(emoticon!.emoji ?? "", forState: UIControlState.Normal)
//            }
            //添加删除按钮 (如果删除按钮的 removeButton的标记 为 yes  添加删除按钮)
            if emoticon!.removeButton {
                emotionButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emotionButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(emotionButton)
        //禁用按钮的点击事件
        emotionButton.userInteractionEnabled = false
        //bounds的基础上 四周缩进4个点
        emotionButton.frame = CGRectInset(bounds, 4, 4)
        emotionButton.backgroundColor = UIColor.whiteColor()
        emotionButton.titleLabel?.font = UIFont.systemFontOfSize(32)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //cell中间的按钮
    lazy var emotionButton = UIButton()
    
}
